﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class EmployeeTarget : System.Web.UI.Page
    {
        #region Fields
        //private static DataTable dtContents;
        //private static GeneralFunctions GF = null;
        private string TblLineName = "tbl_EmpTarget";
        private string HeaderKeyName = "SlpCode";
        private string CurrentPageUrl = "/Business/DataCenter/EmployeeTarget.aspx";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }

                if (!IsPostBack)
                {
                    ClearScreen();

                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    Session["ETGF"] = GF;

                    String dealerId = Request.QueryString["dealer_id"];
                    String slpId = Request.QueryString["slp_id"];
                    String dateTarget = Request.QueryString["date_target"];
                    if (!string.IsNullOrEmpty(dateTarget))
                    {
                        LoadData(dealerId, slpId, dateTarget);
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                   
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["EmpTargetTable"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No='" + lblNo.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["No"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["No"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvSO.EditIndex = -1;
                    BindData((DataTable)Session["EmpTargetTable"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    //DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblIncPmt = (DataTable)Session["IncPmtTable"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            GridViewRow row = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            //this.txtCustomerCode.Text = ((Label)row.FindControl("lblCardCode")).Text; 
                            //this.txtCustomerName.Text = ((Label)row.FindControl("lblCardName")).Text;
                            //this.txtCntctName.Text = ((Label)row.FindControl("lblCntctPrsn")).Text;
                            Session["ChosenBP"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string incPmtId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            //LoadData(incPmtId, ((ulong)DocType.INCOMING).ToString());
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        public DataTable _collectData()
        {
            try
            {
                DataTable tblEmpTarget = (DataTable)Session["EmpTargetTable"];

                DataTable dt = new DataTable("tbl_EmpTarget");
                dt.Columns.Add("SlpCode");
                dt.Columns.Add("ID_Dealer");
                dt.Columns.Add("Comments");
                dt.Columns.Add("DateTarget");
                dt.Columns.Add("QtyTarget");
                dt.Columns.Add("internal_id");

                DataRow rowNew = null;
                Double decQty = 0;
                int liID = 0;
                String lsQty = "0", lsID = "0";

                foreach (DataRow dr in tblEmpTarget.Rows)
                {
                    if (dr["SlpCode"].ToString().Length > 0)
                    {
                        for (int i = 1; i <= 12; i++)
                        {
                            rowNew = dt.NewRow();
                            rowNew["SlpCode"] = dr["SlpCode"];
                            rowNew["ID_Dealer"] = ddlDealer.SelectedValue;
                            rowNew["Comments"] = txtRemarks.Text.Trim();
                            rowNew["DateTarget"] = (i < 10 ? "0" + i.ToString() : i.ToString()) + "/01/" + txtStartMonthYear.Text;
                            // Parse Qty
                            lsQty = dr["QtyTarget_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                            decQty = Double.Parse((String.IsNullOrEmpty(lsQty) || lsQty.Equals("0")) ? "0" : lsQty);
                            rowNew["QtyTarget"] = decQty;
                            // Parse ID
                            lsID = dr["internal_id_" + (i < 10 ? "0" + i.ToString() : i.ToString())].ToString();
                            liID = int.Parse((String.IsNullOrEmpty(lsID) || lsID.Equals("0")) ? "0" : lsID);
                            rowNew["internal_id"] = liID;

                            dt.Rows.Add(rowNew);
                        }
                    }
                }
                
                return dt;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return null;
            }
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["ETGF"];
            DataTable dt = CreateEmpTargetTable();
            if (dtContent != null)
            {
                string SlpCode = String.Empty;
                DataRow newRow = null;

                foreach (DataRow dr in dtContent.Rows)
                {
                    Double decQty = Double.Parse(String.IsNullOrEmpty(dr["QtyTarget"].ToString()) ? "0" : dr["QtyTarget"].ToString());
                    int liinternal_id = int.Parse(String.IsNullOrEmpty(dr["internal_id"].ToString()) ? "0" : dr["internal_id"].ToString());

                    if (SlpCode != dr["SlpCode"].ToString())
                    {
                        if (newRow != null) dt.Rows.Add(newRow);
                        newRow = dt.NewRow();
                        newRow["No"] = (dt.Rows.Count + 1);
                        newRow["SlpCode"] = SlpCode = dr["SlpCode"].ToString();
                        newRow["SlpName"] = dr["SlpName"];
                        newRow["U_Date"] = Convert.ToDateTime(dr["U_Date"].ToString()).ToString("dd/MM/yyyy");
                        newRow["U_Certificate"] = dr["U_Certificate"];
                        newRow["ID_Dealer"] = dr["ID_Dealer"].ToString();
                        newRow["Comments"] = dr["Comments"].ToString();
                        newRow["Total"] = dr["Total"].ToString();
                        newRow["QtyTarget_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["internal_id_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = liinternal_id;
                    }
                    else
                    {
                        newRow["QtyTarget_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = GF.FormatNumeric(decQty.ToString(), "QtyDec");
                        newRow["internal_id_" + Convert.ToDateTime(dr["DateTarget"].ToString(), (new System.Globalization.CultureInfo("es-US")) as CultureInfo).ToString("MM")] = liinternal_id;
                    }
                }
                if (newRow != null) dt.Rows.Add(newRow);
            }
            
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable tblEmpTarget = _collectData();
                if (tblEmpTarget == null || tblEmpTarget.Rows.Count < 1) return;

                Transaction ts = new Transaction();

                DataSet ds = ts.CreateEmpTarget(Utils.AppConstants.DEALER, tblEmpTarget);
                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction obj = new Transaction();
                string error = string.Empty;
                //if (_isPO == "1")
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, false);
                //}
                //else
                //{
                //    //error = obj.CloseCancelPO(int.Parse(_docEntry), _companyCode, isClose, true);
                //}
                //if (error.Length == 0)
                //{
                //    this.lblError.Text = "Operation complete successful!";
                //    DisableControl();
                //}
                //else
                //{
                //    this.lblError.Text = error;
                //}
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        protected void LoadData(string dealer_id, string slp_id, string date_target)
        {
            //string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetEmpTarget(Utils.AppConstants.DEALER, dealer_id, slp_id, date_target);

            if (returnDoc == null || returnDoc.Tables.Count <= 0 )
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtHeader = returnDoc.Tables[0];
            if (returnDoc.Tables[0].Rows.Count > 0)
            {
                DataRow dr = dtHeader.Rows[0];
                txtRemarks.Text = dr["Comments"].ToString();
            }
            DataTable tblEmpTarget = BuildContents(dtHeader);
            BindData(tblEmpTarget);
        }

        protected void LoadDefault()
        {
            //string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = (GeneralFunctions)Session["ETGF"];
            DataTable dtDealers = GF.GetDealers(Utils.AppConstants.VSM, Session[Utils.AppConstants.ID_Dealer].ToString(), "(104)");

            ddlDealer.DataSource = dtDealers;
            ddlDealer.DataValueField = "CardCode";
            ddlDealer.DataTextField = "CardName";
            ddlDealer.DataBind();
            if (ddlDealer.Items.Count > 0)
            {
                ddlDealer.SelectedIndex = 0;
                GF.BindDataSaleMan(Utils.AppConstants.DEALER, ddlDealer.SelectedValue, ddlEmp, "-1");
            }
            // Load detail
            BindData(CreateEmpTargetTable());
        }

        private DataTable CreateEmpTargetTable()
        {
            DataTable tblEmpTarget = new DataTable("tbl_EmpTarget");
            tblEmpTarget = new DataTable("tbl_EmpTarget");
            tblEmpTarget.Columns.Add("No");
            tblEmpTarget.Columns.Add("SlpCode");
            tblEmpTarget.Columns.Add("SlpName");
            tblEmpTarget.Columns.Add("U_Date");
            tblEmpTarget.Columns.Add("U_Certificate");
            tblEmpTarget.Columns.Add("ID_Dealer");
            tblEmpTarget.Columns.Add("Comments");
            tblEmpTarget.Columns.Add("Total");
            tblEmpTarget.Columns.Add("QtyTarget_01");
            tblEmpTarget.Columns.Add("QtyTarget_02");
            tblEmpTarget.Columns.Add("QtyTarget_03");
            tblEmpTarget.Columns.Add("QtyTarget_04");
            tblEmpTarget.Columns.Add("QtyTarget_05");
            tblEmpTarget.Columns.Add("QtyTarget_06");
            tblEmpTarget.Columns.Add("QtyTarget_07");
            tblEmpTarget.Columns.Add("QtyTarget_08");
            tblEmpTarget.Columns.Add("QtyTarget_09");
            tblEmpTarget.Columns.Add("QtyTarget_10");
            tblEmpTarget.Columns.Add("QtyTarget_11");
            tblEmpTarget.Columns.Add("QtyTarget_12");

            tblEmpTarget.Columns.Add("internal_id_01");
            tblEmpTarget.Columns.Add("internal_id_02");
            tblEmpTarget.Columns.Add("internal_id_03");
            tblEmpTarget.Columns.Add("internal_id_04");
            tblEmpTarget.Columns.Add("internal_id_05");
            tblEmpTarget.Columns.Add("internal_id_06");
            tblEmpTarget.Columns.Add("internal_id_07");
            tblEmpTarget.Columns.Add("internal_id_08");
            tblEmpTarget.Columns.Add("internal_id_09");
            tblEmpTarget.Columns.Add("internal_id_10");
            tblEmpTarget.Columns.Add("internal_id_11");
            tblEmpTarget.Columns.Add("internal_id_12");
            return tblEmpTarget;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["EmpTargetTable"] = tblData;
            this.grvSO.DataSource = tblData;
            this.grvSO.DataBind();
        }

        protected void ClearScreen()
        {
            txtRemarks.Text = String.Empty;
            BindData(CreateEmpTargetTable());
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnSave.Enabled =
                    btnCancel.Enabled = 
                    btnAddItems.Enabled = true;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnAddItems.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "C";
                    break;

                case "Close":
                    btnSave.Enabled = 
                    btnCancel.Enabled =
                    btnAddItems.Enabled = false;
                    hdnStatus.Value = "C";
                    break;
            }
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvSO.PageIndex = e.NewPageIndex;
            DataTable tblEmpTarget = (DataTable)Session["EmpTargetTable"];
            BindData(tblEmpTarget);
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    if (this.hdnStatus.Value == "C")
            //    {
            //        LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
            //        if (lnkDelete != null) lnkDelete.Enabled = false;
            //    }
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                // Default Dealer DB: Load Employees 
                //DropDownList ddlEmployees = (DropDownList)e.Row.FindControl("ddlEmployees");
                // Get quantity
                double qty1 = 0, qty2 = 0, qty3 = 0, qty4 = 0, qty5 = 0, qty6 = 0, qty7 = 0, qty8 = 0, qty9 = 0, qty10 = 0, qty11 = 0, qty12 = 0;
                TextBox txtQty01 = (TextBox)e.Row.FindControl("txtQuantity_01");
                TextBox txtQty02 = (TextBox)e.Row.FindControl("txtQuantity_02");
                TextBox txtQty03 = (TextBox)e.Row.FindControl("txtQuantity_03");
                TextBox txtQty04 = (TextBox)e.Row.FindControl("txtQuantity_04");
                TextBox txtQty05 = (TextBox)e.Row.FindControl("txtQuantity_05");
                TextBox txtQty06 = (TextBox)e.Row.FindControl("txtQuantity_06");
                TextBox txtQty07 = (TextBox)e.Row.FindControl("txtQuantity_07");
                TextBox txtQty08 = (TextBox)e.Row.FindControl("txtQuantity_08");
                TextBox txtQty09 = (TextBox)e.Row.FindControl("txtQuantity_09");
                TextBox txtQty10 = (TextBox)e.Row.FindControl("txtQuantity_10");
                TextBox txtQty11 = (TextBox)e.Row.FindControl("txtQuantity_11");
                TextBox txtQty12 = (TextBox)e.Row.FindControl("txtQuantity_12");
                Label lblTotal = (Label)e.Row.FindControl("lblTotal");
                if (lblTotal != null)
                {
                    if (txtQty01 != null) double.TryParse(txtQty01.Text.Trim(), out qty1);
                    if (txtQty02 != null) double.TryParse(txtQty02.Text.Trim(), out qty2);
                    if (txtQty03 != null) double.TryParse(txtQty03.Text.Trim(), out qty3);
                    if (txtQty04 != null) double.TryParse(txtQty04.Text.Trim(), out qty4);

                    if (txtQty05 != null) double.TryParse(txtQty05.Text.Trim(), out qty5);
                    if (txtQty06 != null) double.TryParse(txtQty06.Text.Trim(), out qty6);
                    if (txtQty07 != null) double.TryParse(txtQty07.Text.Trim(), out qty7);
                    if (txtQty08 != null) double.TryParse(txtQty08.Text.Trim(), out qty8);

                    if (txtQty09 != null) double.TryParse(txtQty09.Text.Trim(), out qty9);
                    if (txtQty10 != null) double.TryParse(txtQty10.Text.Trim(), out qty10);
                    if (txtQty11 != null) double.TryParse(txtQty11.Text.Trim(), out qty11);
                    if (txtQty12 != null) double.TryParse(txtQty12.Text.Trim(), out qty12);

                    lblTotal.Text = (qty1 + qty2 + qty3 + qty4 + qty5 + qty6 + qty7 + qty8 + qty9 + qty10 + qty11 + qty12).ToString();
                
                }

            }
        }

        protected void ddlDealer_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Default Dealer DB: Load Employees 
            ((GeneralFunctions)Session["ETGF"]).BindDataSaleMan(Utils.AppConstants.DEALER, ddlDealer.SelectedValue, ddlEmp, "-1");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtQtyTarget_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                // Get quantity
                TextBox txtQty01 = (TextBox)row.FindControl("txtQuantity_01");
                TextBox txtQty02 = (TextBox)row.FindControl("txtQuantity_02");
                TextBox txtQty03 = (TextBox)row.FindControl("txtQuantity_03");
                TextBox txtQty04 = (TextBox)row.FindControl("txtQuantity_04");
                TextBox txtQty05 = (TextBox)row.FindControl("txtQuantity_05");
                TextBox txtQty06 = (TextBox)row.FindControl("txtQuantity_06");
                TextBox txtQty07 = (TextBox)row.FindControl("txtQuantity_07");
                TextBox txtQty08 = (TextBox)row.FindControl("txtQuantity_08");
                TextBox txtQty09 = (TextBox)row.FindControl("txtQuantity_09");
                TextBox txtQty10 = (TextBox)row.FindControl("txtQuantity_10");
                TextBox txtQty11 = (TextBox)row.FindControl("txtQuantity_11");
                TextBox txtQty12 = (TextBox)row.FindControl("txtQuantity_12");
                // Get ID
                HiddenField hdnInternalID_01 = (HiddenField)row.FindControl("hdnInternalID_01");
                HiddenField hdnInternalID_02 = (HiddenField)row.FindControl("hdnInternalID_02");
                HiddenField hdnInternalID_03 = (HiddenField)row.FindControl("hdnInternalID_03");
                HiddenField hdnInternalID_04 = (HiddenField)row.FindControl("hdnInternalID_04");
                HiddenField hdnInternalID_05 = (HiddenField)row.FindControl("hdnInternalID_05");
                HiddenField hdnInternalID_06 = (HiddenField)row.FindControl("hdnInternalID_06");
                HiddenField hdnInternalID_07 = (HiddenField)row.FindControl("hdnInternalID_07");
                HiddenField hdnInternalID_08 = (HiddenField)row.FindControl("hdnInternalID_08");
                HiddenField hdnInternalID_09 = (HiddenField)row.FindControl("hdnInternalID_09");
                HiddenField hdnInternalID_10 = (HiddenField)row.FindControl("hdnInternalID_10");
                HiddenField hdnInternalID_11 = (HiddenField)row.FindControl("hdnInternalID_11");
                HiddenField hdnInternalID_12 = (HiddenField)row.FindControl("hdnInternalID_12");

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblEmpTarget = (DataTable)Session["EmpTargetTable"];

                if (tblEmpTarget != null)
                {
                    DataRow[] rupdate = tblEmpTarget.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        // update qty
                        rupdate[0]["QtyTarget_01"] = (txtQty01 != null ? txtQty01.Text : "0");
                        rupdate[0]["QtyTarget_02"] = (txtQty02 != null ? txtQty02.Text : "0");
                        rupdate[0]["QtyTarget_03"] = (txtQty04 != null ? txtQty03.Text : "0");
                        rupdate[0]["QtyTarget_04"] = (txtQty04 != null ? txtQty04.Text : "0");
                        rupdate[0]["QtyTarget_05"] = (txtQty05 != null ? txtQty05.Text : "0");
                        rupdate[0]["QtyTarget_06"] = (txtQty06 != null ? txtQty06.Text : "0");
                        rupdate[0]["QtyTarget_07"] = (txtQty07 != null ? txtQty07.Text : "0");
                        rupdate[0]["QtyTarget_08"] = (txtQty08 != null ? txtQty08.Text : "0");
                        rupdate[0]["QtyTarget_09"] = (txtQty09 != null ? txtQty09.Text : "0");
                        rupdate[0]["QtyTarget_10"] = (txtQty10 != null ? txtQty10.Text : "0");
                        rupdate[0]["QtyTarget_11"] = (txtQty11 != null ? txtQty11.Text : "0");
                        rupdate[0]["QtyTarget_12"] = (txtQty12 != null ? txtQty12.Text : "0");
                        // update ID
                        rupdate[0]["internal_id_01"] = (hdnInternalID_01 != null ? hdnInternalID_01.Value : "0");
                        rupdate[0]["internal_id_02"] = (hdnInternalID_02 != null ? hdnInternalID_02.Value : "0");
                        rupdate[0]["internal_id_03"] = (hdnInternalID_03 != null ? hdnInternalID_03.Value : "0");
                        rupdate[0]["internal_id_04"] = (hdnInternalID_04 != null ? hdnInternalID_04.Value : "0");
                        rupdate[0]["internal_id_05"] = (hdnInternalID_05 != null ? hdnInternalID_05.Value : "0");
                        rupdate[0]["internal_id_06"] = (hdnInternalID_06 != null ? hdnInternalID_06.Value : "0");
                        rupdate[0]["internal_id_07"] = (hdnInternalID_07 != null ? hdnInternalID_07.Value : "0");
                        rupdate[0]["internal_id_08"] = (hdnInternalID_08 != null ? hdnInternalID_08.Value : "0");
                        rupdate[0]["internal_id_09"] = (hdnInternalID_09 != null ? hdnInternalID_09.Value : "0");
                        rupdate[0]["internal_id_10"] = (hdnInternalID_10 != null ? hdnInternalID_10.Value : "0");
                        rupdate[0]["internal_id_11"] = (hdnInternalID_11 != null ? hdnInternalID_11.Value : "0");
                        rupdate[0]["internal_id_12"] = (hdnInternalID_12 != null ? hdnInternalID_12.Value : "0");
                    }
                }

                this.grvSO.EditIndex = -1;
                BindData(tblEmpTarget);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tblEmpTarget = (DataTable)Session["EmpTargetTable"];
            if (tblEmpTarget == null) tblEmpTarget = CreateEmpTargetTable();
            
            DataRow rowNew = tblEmpTarget.NewRow();
            rowNew["No"] = (tblEmpTarget.Rows.Count + 1).ToString();
            rowNew["SlpCode"] = ddlEmp.SelectedValue;
            rowNew["QtyTarget_01"] =
            rowNew["QtyTarget_02"] =
            rowNew["QtyTarget_03"] =
            rowNew["QtyTarget_04"] = 
            rowNew["QtyTarget_05"] =
            rowNew["QtyTarget_06"] =
            rowNew["QtyTarget_07"] =
            rowNew["QtyTarget_08"] = 
            rowNew["QtyTarget_09"] = 
            rowNew["QtyTarget_10"] =
            rowNew["QtyTarget_11"] = 
            rowNew["QtyTarget_12"] = 0;
            rowNew["internal_id_01"] =
            rowNew["internal_id_02"] =
            rowNew["internal_id_03"] =
            rowNew["internal_id_04"] =
            rowNew["internal_id_05"] =
            rowNew["internal_id_06"] =
            rowNew["internal_id_07"] =
            rowNew["internal_id_08"] =
            rowNew["internal_id_09"] =
            rowNew["internal_id_10"] =
            rowNew["internal_id_11"] =
            rowNew["internal_id_12"] = 0;
            tblEmpTarget.Rows.Add(rowNew);
            BindData(tblEmpTarget);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData(ddlDealer.SelectedValue, ddlEmp.SelectedValue.Equals("-1") ? "" : ddlEmp.SelectedValue, txtStartMonthYear.Text);
        }
    }
}